package TestPark;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import jdbcutil.JDBCUtil;

public class RecordingDao {
	Connection conn = null;
	PreparedStatement ps = null;
	
	public Integer insert(RecordingModel model) {
		String sql = "insert into test.recording(id,carId,fare,befDate,aftDate)values(?,?,?,?,?)";
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, model.getId());
			ps.setString(2, model.getCarId());
			ps.setDouble(3, model.getFare());	
			ps.setTimestamp(4, model.getBefDate());
			ps.setTimestamp(5, model.getAftDate());	
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return null;
	}
	
	public List<RecordingModel> selectList() {
		List<RecordingModel> list = new ArrayList<>();
		StringBuffer sql = new StringBuffer("select id,carId,fare,befDate,aftDate from test.recording");
		ResultSet rs = null;
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			rs = ps.executeQuery();
			while (rs.next()) {
				RecordingModel mod = new RecordingModel();
				mod.setId(rs.getInt("id"));
				mod.setCarId(rs.getString("carId"));
				mod.setFare(rs.getDouble("fare"));
				mod.setBefDate(rs.getTimestamp("befDate"));
				mod.setAftDate(rs.getTimestamp("aftDate"));
				list.add(mod);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps, rs);
		}
		return list;
	}
	
	public Integer update(RecordingModel model) {
		StringBuffer sql = new StringBuffer("update test.recording");
		List<Object> vals = appendSet(sql,model);
		try {
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(sql.toString());
			for (int i = 0; i < vals.size(); i++) {
				ps.setObject(i + 1, vals.get(i));
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return null;
	}
	
	private List<Object> appendSet(StringBuffer sql, RecordingModel model) {
		sql.append(" set id = id ");
		List<Object> objs = new ArrayList<Object>();
		Timestamp aftDate = model.getAftDate();
		sql.append(",aftDate = ? ");
		objs.add(aftDate);

		double fare = model.getFare();
		sql.append(",fare = ? ");
		objs.add(fare);

		sql.append(" where 1 = 1 ");
		int id = model.getId();
		sql.append("and id = ? ");
		objs.add(id);

		String carId = model.getCarId();
		sql.append("and carId = ? ");
		objs.add(carId);
		return objs;
	}
}
